import type { App, Directive, DirectiveBinding } from 'vue'
import router from '@/router'
/** 不可直接使用 useRoute useRoute 只能使用在 setup 中 */

// 验证权限
const matchPermission = (value: string) => {
  const permission = router.currentRoute.value.meta.permission as any[]
  const permissionIdList = permission.map((perm) => perm.id)

  return permissionIdList.includes(value)
}

const hasPermission = (el: Element, binding: DirectiveBinding) => {
  const value = binding.value
  const hasPermission = matchPermission(value)
  if (!hasPermission) {
    el.parentNode?.removeChild(el)
  }
}

const mounted = (el: Element, binding: DirectiveBinding) => {
  hasPermission(el, binding)
}

// 生命周期
const permissionDirective: Directive = {
  mounted,
}

// 添加指令
export const setupPermissionDirective = (app: App<Element>) => {
  app.directive('permission', permissionDirective)
}
